import React, { useState, useEffect, useRef } from 'react';
import { Form, Input, Button, Avatar, List, message, Spin, Modal } from 'antd';
import { UserOutlined, LikeOutlined, CommentOutlined, LikeFilled, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { famousPersonId } from '@/services';
import styles from './index.less';
import { getMessageBoardList, publishMessageBoard, likeMessageBoard, unlikeMessageBoard, MessageBoardInfo, deleteMessageBoard, updateMessageBoard  } from '@/services/MessageBoardService';
const { TextArea } = Input;

const MessageBoard: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [data, setData] = useState<MessageBoardInfo[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const containerRef = useRef<HTMLDivElement>(null);
  const loadingRef = useRef(false);
  const [editingMessage, setEditingMessage] = useState<MessageBoardInfo | null>(null);

  // 获取留言列表
  const fetchMessages = async (page = 1, isLoadMore = false) => {
    if (loadingRef.current) return;
    loadingRef.current = true;
    setLoading(true);
    try {
      const response = await getMessageBoardList({
        pageCurrent: page,
        pageSize: 10,
        famousPersonId
      });
      
      if (isLoadMore) {
        setData(prev => [...prev, ...(response.list || [])]);
      } else {
        setData(response.list || []);
      }
      
      setHasMore(response.totalCount > page * 10);
      setCurrentPage(page);
    } catch (error) {
      message.error('获取留言失败');
    } finally {
      setLoading(false);
      loadingRef.current = false;
    }
  }

  // 提交留言
  const handleSubmit = async (values: any) => {
    if (!values.content?.trim()) {
      message.warning('请输入留言内容');
      return;
    }

    try {
      setSubmitting(true);
      const res = await publishMessageBoard({
        content: values.content,
        famousPersonId
      });
      
      if (res) {
        message.success('留言成功');
        form.resetFields();
        // 重置页码并重新获取数据
        setCurrentPage(1);
        setHasMore(true);
        await fetchMessages(1, false);
      }
    } catch (error) {
      message.error('发布留言失败');
    } finally {
      setSubmitting(false);
    }
  };

  // 点赞/取消点赞
  const handleLike = async (item: MessageBoardInfo) => {
    // 保存原始状态，以便失败时回滚
    const originalIsLike = item.isLike;
    const originalLikeCount = item.likeCount || 0;

    // 乐观更新UI
    setData(prevData => 
      prevData.map(message => 
        message.id === item.id 
          ? {
              ...message,
              isLike: !message.isLike,
              likeCount: message.likeCount + (message.isLike ? -1 : 1)
            }
          : message
      )
    );

    try {
      // 调用接口
      const res = item.isLike
        ? await unlikeMessageBoard(item.id)
        : await likeMessageBoard(item.id);
      
      if (!res) {
        // 如果接口失败，回滚状态
        setData(prevData =>
          prevData.map(message =>
            message.id === item.id
              ? {
                  ...message,
                  isLike: originalIsLike,
                  likeCount: originalLikeCount
                }
              : message
          )
        );
        throw new Error('操作失败');
      }
    } catch (error: any) {
      message.error(error.message || '操作失败');
    }
  };

  // 处理编辑
  const handleEdit = (item: MessageBoardInfo) => {
    setEditingMessage(item);
    form.setFieldsValue({ editContent: item.content });
  };

  // 处理删除
  const handleDelete = (item: MessageBoardInfo) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条留言吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          // TODO: 调用删除接口
          await deleteMessageBoard(item.id);
          message.success('删除成功');
          await fetchMessages(currentPage, false);
        } catch (error) {
          message.error('删除失败');
        }
      }
    });
  };

  // 渲染操作按钮
  const renderActions = (item: MessageBoardInfo) => {
    const actions = [
      <Button
        key="like"
        type="text"
        icon={item.isLike ? <LikeFilled style={{ color: '#1890ff' }} /> : <LikeOutlined />}
        onClick={() => handleLike(item)}
        className={item.isLike ? styles.liked : ''}
      >
        {item.likeCount || 0}
      </Button>
    ];

    // 如果是当前用户的留言，添加编辑和删除按钮
    if (item.isCurrentUser) {
      actions.push(
        <Button
          key="edit"
          type="text"
          icon={<EditOutlined />}
          onClick={() => handleEdit(item)}
        >
          编辑
        </Button>,
        <Button
          key="delete"
          type="text"
          icon={<DeleteOutlined />}
          onClick={() => handleDelete(item)}
          danger
        >
          删除
        </Button>
      );
    }

    return actions;
  };

  // 滚动加载
  const handleScroll = () => {
    if (!containerRef.current || loading || !hasMore || loadingRef.current) return;

    const container = containerRef.current;
    const { scrollTop, clientHeight, scrollHeight } = container;
    const scrollThreshold = 100;

    if (scrollHeight - scrollTop - clientHeight < scrollThreshold) {
      fetchMessages(currentPage + 1, true);
    }
  };

  useEffect(() => {
    fetchMessages();
  }, []);

  useEffect(() => {
    const container = containerRef.current;
    if (container) {
      container.addEventListener('scroll', handleScroll);
      return () => container.removeEventListener('scroll', handleScroll);
    }
  }, [loading, hasMore, currentPage]);

  return (
    <div className={styles.messageBoardContainer}>
      <div className={styles.messageForm}>
        <Form form={form} onFinish={handleSubmit}>
          <Form.Item name="content">
            <TextArea
              placeholder="说点什么吧..."
              autoSize={{ minRows: 3, maxRows: 6 }}
              maxLength={500}
              showCount
            />
          </Form.Item>
          <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
            <Button
              type="primary"
              htmlType="submit"
              loading={submitting}
            >
              发表留言
            </Button>
          </Form.Item>
        </Form>
      </div>

      <div className={styles.messageList} ref={containerRef}>
        <List
          dataSource={data}
          renderItem={item => (
            <List.Item 
              key={item.id} 
              className={styles.messageItem}
              actions={renderActions(item)}
            >
              <List.Item.Meta
                avatar={
                  item.userAvatar ? <Avatar src={item.userAvatar} /> : <Avatar icon={<UserOutlined />} />
                }
                title={
                  <div className={styles.messageHeader}>
                    <span className={styles.username}>{item.username || '匿名用户'}</span>
                    <span className={styles.time}>
                      {item.time}
                    </span>
                  </div>
                }
                description={
                  <div className={styles.messageContent}>
                    <div className={styles.content}>{item.content}</div>
                  </div>
                }
              />
            </List.Item>
          )}
        />

        {loading && (
          <div className={styles.loadingMore}>
            <Spin />
            <span>加载中...</span>
          </div>
        )}

        {!hasMore && data.length > 0 && (
          <div className={styles.noMore}>
            没有更多留言了
          </div>
        )}
      </div>

      {/* 编辑留言的弹窗 */}
      <Modal
        title="编辑留言"
        open={!!editingMessage}
        onCancel={() => setEditingMessage(null)}
        onOk={async () => {
          try {
            const { editContent } = await form.validateFields(['editContent']);
            // TODO: 调用编辑接口
            await updateMessageBoard({
              id: editingMessage?.id,
              content: editContent
            });
            message.success('编辑成功');
            setEditingMessage(null);
            await fetchMessages(currentPage, false);
          } catch (error) {
            message.error('编辑失败');
          }
        }}
      >
        <Form form={form}>
          <Form.Item
            name="editContent"
            rules={[{ required: true, message: '请输入留言内容' }]}
          >
            <TextArea
              autoSize={{ minRows: 3, maxRows: 6 }}
              maxLength={500}
              showCount
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default MessageBoard; 